package jp.seraph.jsade.net;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.charset.Charset;

import jp.seraph.jsade.message.MessageUtil;

/**
 * RoboCupSocketのデフォルト実装
 */
public class DefaultRoboCupSocket implements RoboCupSocket {
    public DefaultRoboCupSocket(){
    }

    private Socket mSocket;

    /**
     *
     * @see jp.seraph.jsade.net.RoboCupSocket#connect()
     */
    public void connect(SocketAddress aAddress) throws IOException {
        if(mSocket != null)
            throw new IllegalStateException(MessageUtil.alreadyConnected());

        mSocket = new Socket();
        mSocket.connect(aAddress);
    }

    public String read() throws IOException {
        DataInputStream tReader = new DataInputStream(mSocket.getInputStream());
        int tBodyLength = tReader.readInt();

        byte[] tBodyData = new byte[tBodyLength];
        int tReadLength = 0;

        do {
            tReadLength += tReader.read(tBodyData, tReadLength, tBodyLength - tReadLength);
        } while (tReadLength < tBodyLength);

        return new String(tBodyData, Charset.defaultCharset().name());
    }

    public int write(String aData) throws IOException {
        if ("".equals(aData))
            return 0;

        byte[] tDataBytes = aData.getBytes();
        int tLength = tDataBytes.length;
        DataOutputStream tWriter = new DataOutputStream(mSocket.getOutputStream());
        tWriter.writeInt(tDataBytes.length);
        tWriter.write(tDataBytes);
        tWriter.flush();
        return tLength + 4;
    }

    public void close() {
        if (mSocket != null) {
            try {
                mSocket.close();
                mSocket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
